package com.highcom.controller;

import com.alibaba.fastjson.JSON;
import com.highcom.config.RedisConfig;
import com.highcom.constant.MessageConstant;
import com.highcom.constant.RedisMessageConstant;
import com.highcom.entity.Result;
import com.highcom.model.Member;
import com.highcom.service.MemberService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import java.util.Date;
import java.util.Map;

/**
 * @version 1.0
 * @Author YangJiaQuan_hrbnu
 * @Date 2024/8/7 14:57
 */
@RestController
@RequestMapping("/member")
public class MemberController {

    private static JedisPool jedisPool;
    @Autowired
    private RedisConfig redisConfig;
    @PostConstruct
    public void init(){
        jedisPool = redisConfig.redisPoolFactory();
    }
    @Resource
    private MemberService memberService;

    @RequestMapping("/login")   //登录逻辑：验证验证码，判断是否会员，加入cookie，redis写入会员信息
    public Result login(@RequestBody Map map, HttpServletResponse response){
        String telephone = (String) map.get("telephone");
        String validateCode = (String) map.get("validateCode");
        //  从redis获取验证码
        String validateCodeByRedis = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_LOGIN);
        if(validateCode != null && validateCodeByRedis != null && validateCode.equals(validateCodeByRedis)){
            //  检查是否是会员
            Member member = memberService.findByTelephone(telephone);
            if(member == null){
                member.setRegTime(new Date());
                member.setPhoneNumber(telephone);
                memberService.add(member);
            }
            //  向浏览器写入cookie
            Cookie cookie = new Cookie("login_member_telephone",telephone);
            cookie.setPath("/");
            cookie.setMaxAge(60*60*24*30);
            response.addCookie(cookie);
            //  将会员信息写入redis
            String json = JSON.toJSON(member).toString();
            jedisPool.getResource().setex(telephone,60*30,json);
            return new Result(true, MessageConstant.LOGIN_SUCCESS);
        }else{
            return new Result(false,MessageConstant.VALIDATECODE_ERROR);
        }
    }
}
